package com.opages.netty.demo.netty.stickybag;

import com.opages.netty.demo.netty.codec.ByteToLongDecoder;
import com.opages.netty.demo.netty.codec.LongToByteEncoder;
import com.opages.netty.demo.netty.codec.ServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author daizhong.liu
 * @create 2021-12-14 15:27
 **/
public class NettyService {

    public void start() {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            serverBootstrap.group(bossGroup,workerGroup)
                .option(ChannelOption.SO_BACKLOG,128)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast(new MessageEncoder())
                                .addLast(new MessageDecoder())
                                .addLast(new ServerProtocolHandler());

                    }
            });
            ChannelFuture channelFuture = serverBootstrap.bind(9998).sync();
            channelFuture.addListener(listen -> {
                if(listen.isSuccess()) {
                    System.err.println("启动成功!");
                }else {
                    System.err.println("失败!");
                }
            });
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        NettyService nettyService = new NettyService();
        nettyService.start();
    }
}
